package cv.vender.http;


import android.annotation.SuppressLint;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Base64;

import java.io.ByteArrayOutputStream;

import java.io.IOException;
import java.io.InputStream;

import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Calendar;

import cv.vender.LocalTradeUtils;

import cv.vender.clsCmdConst;
import cv.vender.clsToolBox;
import cv.vender.clsPublicPara;
import cv.vender.http.bean.clsGetQrcodePara;
import cv.vender.http.bean.clsGoodsPara;
import cv.vender.http.bean.clsSendTradeToPc;

public class clscvhttp extends Thread
{

	public static final int HTTP_CMD_VENDER=1;
	public static final int HTTP_CMD_TRADE=2;
	public static final int HTTP_CMD_GOODS=3;
	public static final int HTTP_CMD_SLOT=4;
	public static final int HTTP_CMD_QRCODE=5;
	public static final int HTTP_CMD_GET_PAY_RESULT=6;
	public static final int HTTP_CMD_GET_FETCH_CODE=7;
	public static final int HTTP_CMD_SYNC_TIME=8;
	public static final int HTTP_CMD_REQUEST_SLOT=9;
	public static final int HTTP_CMD_SINGLE_QRCODE=10;
	public static final int HTTP_CMD_HEART=11;
	public static final int HTTP_CMD_MAKE_SWIPE_TRADE=12;
	private static final String TAG = "clscvhttp";
	private static clscvhttp instance;
	URL url = null;
	boolean connect = false;
	private Handler mChildHandler;
	private String serverurl;
	private int FrameId = 0;

	/*
	 * Function  :   处理服务器的响应结果（将输入流转化成字符串）
	 * Param     :   inputStream服务器的响应输入流
	 */
	public static String dealResponseResult(InputStream inputStream) {
		String resultData = null;      //存储处理结果
		ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
		byte[] data = new byte[102400];//100k的大小
		int len = 0;
		try {
			while ((len = inputStream.read(data)) != -1) {
				byteArrayOutputStream.write(data, 0, len);
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		resultData = new String(byteArrayOutputStream.toByteArray());
		return resultData;
	}

	public static clscvhttp getInstance() {

		if (instance == null) {
			instance = new clscvhttp();
		}

		return instance;
	}

	public void init(String urlstr) {
		try {
			url = new URL(urlstr);
		} catch (MalformedURLException e) {
			e.printStackTrace();
		}
		instance.setName("联网通信线程");
		serverurl = urlstr;
		instance.start();
	}

	@SuppressLint("HandlerLeak")
	public void run() {
		Looper.prepare();

		setmChildHandler(new Handler() {
			@Override
			public void handleMessage(Message msg) {
				try {
					switch(msg.what) {
						case HTTP_CMD_VENDER:
							GenerateVenderPost((clsHttpFrame)msg.obj);
							break;
						case HTTP_CMD_TRADE:
							GenerateTrade((clsHttpFrame)msg.obj);
							break;
						case HTTP_CMD_GOODS:
							//GenerateGoodsRequest((clsHttpFrame)msg.obj);
							break;
						case HTTP_CMD_SLOT:
							GenerateSlotSend((clsHttpFrame)msg.obj);
							break;
						case HTTP_CMD_QRCODE:
							//生成二维码
							GenerateQrcode((clsHttpFrame)msg.obj);
							break;
						case HTTP_CMD_SINGLE_QRCODE:
							GenerateSingleQrcode((clsHttpFrame)msg.obj);
							break;

						case HTTP_CMD_GET_PAY_RESULT:
                				/*查询支付状态*/
							GeneratePollResult((clsHttpFrame)msg.obj);
							break;

						case HTTP_CMD_GET_FETCH_CODE:
                				/*验证出货码*/
							GenerateVerifyResult((clsHttpFrame)msg.obj);

							break;
						case HTTP_CMD_SYNC_TIME:
                				/*同步时间*/
							GenerateSyncTime((clsHttpFrame)msg.obj);
							break;
						case HTTP_CMD_REQUEST_SLOT:
                				/*获取单个货道信息*/
							GenerateSlotRequest((clsHttpFrame)msg.obj);

							break;
						case HTTP_CMD_HEART:
                				/*服务器返回事件内容*/
							GenerateHeartRequest((clsHttpFrame)msg.obj);

							break;
						case HTTP_CMD_MAKE_SWIPE_TRADE:
                				/*发送刷卡支付请求*/
							GenerateSwipeTradeRequest((clsHttpFrame)msg.obj);

							break;
						default:
                				/*启动下一次poll*/
							break;
					}
				} catch (Exception e) {
					e.printStackTrace();
				}
			}

			private void GenerateVenderPost(clsHttpFrame obj) {
				String objstr = obj.ToBase64String();
				clsToolBox.println(objstr);
				String ret= PostData(objstr);
				String response= CopeResponse(ret, obj.getFid());
				clsToolBox.println(response);

			}

			private void GenerateSlotSend(clsHttpFrame obj) {
				String objstr = obj.ToBase64String();
				clsToolBox.println(objstr);
				String ret= PostData(objstr);

				String response= CopeResponse(ret, obj.getFid());
				clsToolBox.println(response);
			}

			private String CopeResponse(String ret,int s_fid) {
				if(ret==null) {
					return  null;
				}
				String[] retpara=ret.split(",");
				if(retpara.length!=3) {
					clsToolBox.println("数组长度不对");
					return null;
				}
				int fid=clsToolBox.ParseInt(retpara[0]);
				int length=clsToolBox.ParseInt(retpara[1]);

				if(s_fid!=fid) {
					clsToolBox.println("消息编号不对");
					return null;
				}

				if(retpara[2].length()!=length) {
					clsToolBox.println("消息长度不对");
					return null;
				}

				String orig_string = null;
				try {
					orig_string = new String(Base64.decode(retpara[2].getBytes("GBK"),Base64.DEFAULT),"GBK");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}
				return orig_string;
			}

			private void GenerateVerifyResult(clsHttpFrame obj) {
				String objstr = obj.ToBase64String();

				clsToolBox.println(objstr);
				String ret= PostData(objstr);
				String response= CopeResponse(ret, obj.getFid());
				clsToolBox.println(response);
			}

			private void GenerateTrade(clsHttpFrame obj) {
				String objstr = obj.ToBase64String();
				clsToolBox.println(objstr);
				String ret= PostData(objstr);
				String response= CopeResponse(ret, obj.getFid());

				if(response==null) {
					response="0";
				}
				clsToolBox.println(response);
				if(!response.equals("1")) {
					//如果数据发送失败，就先保存起来
					LocalTradeUtils.SaveHttpTradeDataToFile(obj.getData_str());
				}
			}


			private void GenerateSyncTime(clsHttpFrame obj) {
				String objstr = obj.ToBase64String();
				clsToolBox.println(objstr);
				String ret= PostData(objstr);
				String response= CopeResponse(ret, obj.getFid());
				clsToolBox.println(response);
			}

			private void GeneratePollResult(clsHttpFrame obj) {
				String objstr = obj.ToBase64String();
				clsToolBox.println(objstr);
				String ret= PostData(objstr);
				String response= CopeResponse(ret, obj.getFid());
				clsToolBox.println(response);
			}

			//生成二维码
			private void GenerateQrcode(clsHttpFrame obj) {
				String objstr = obj.ToBase64String();
				clsToolBox.println(objstr);
				String ret= PostData(objstr);
				String response= CopeResponse(ret, obj.getFid());
				Handler handler = clsPublicPara.MainHandler;
				Message message = handler.obtainMessage(clsCmdConst.CMD_HTTP_FRESH_QRCODE, response);
				if(response!=null) {
					if(response.startsWith("QRCODE")) {
						message.arg1 = 1;
					}
				}
				message.sendToTarget();
			}


			//从服务器上获取到的订单
			protected void GenerateTradeRequest(clsHttpFrame obj) {
				String objstr = obj.ToBase64String();
				String ret= PostData(objstr);
				String response= CopeResponse(ret, obj.getFid());
				Handler handler= clsPublicPara.MainHandler;
				Message message=handler.obtainMessage();
				message.what=clsCmdConst.CMD_HTTP_POLL_TRADE;
				if(response!=null) {
					String[] arr=response.split(",",-1);
					if(arr.length==5) {
						/*交易编号,购买重量,商品名称,支付金额,用户名,支付方式*/
						clsSendTradeToPc trsfortradepara=new clsSendTradeToPc();
						trsfortradepara.setTradeId(arr[0]);
						trsfortradepara.setSlotid(clsToolBox.ParseInt(arr[1]));
						trsfortradepara.setGoodsname(arr[2]);
						trsfortradepara.setCashAmount(clsToolBox.ParseInt(arr[3]));
						trsfortradepara.setUser(arr[4]);
						trsfortradepara.setPayTyp(clsToolBox.ParseInt(arr[5]));
						trsfortradepara.setDatetime(Calendar.getInstance());
						message.arg1=1;
						message.obj=trsfortradepara;
						handler.sendMessage(message);
						return ;
					} else {
						message.obj="数组长度无效";
					}
				} else {
					message.obj="数据获取失败";
				}
				message.arg1=0;
				handler.sendMessage(message);
				return ;
			}


			private void GenerateSingleQrcode(clsHttpFrame obj) {
				String objstr = obj.ToBase64String();
				clsToolBox.println(objstr);
				String ret= PostData(objstr);
				String response= CopeResponse(ret, obj.getFid());

				Handler handler= clsPublicPara.MainHandler;
				Message message=handler.obtainMessage();
				message.what=clsCmdConst.CMD_HTTP_FRESH_QRCODE;
				if(response!=null) {
					String[] arr=response.split(",",-1);
					if(arr.length==3) {
						//QRCODEhttps://qr.alipay.com/bax094456teolklivlkg208b,2016070800334666000030161,
						if(arr[0].startsWith("QRCODE")) {
							clsGetQrcodePara tradepara=new clsGetQrcodePara();
							tradepara.setPayTyp(clsToolBox.ParseInt(arr[2]));
							tradepara.setTradeId(arr[1]);

							tradepara.setQrcode(arr[0].substring(6));
							message.arg1=1;
							message.obj=tradepara;
							handler.sendMessage(message);
							return ;
						} else {
							message.obj="数据头无效";
						}
					} else {
						message.obj="数组长度无效";
					}
				} else {
					message.obj="数据获取失败";
				}
				message.arg1=0;
				handler.sendMessage(message);
				return ;
			}

			private void GenerateSlotRequest(clsHttpFrame obj) {
				String objstr = obj.ToBase64String();
				clsToolBox.println(objstr);
				String ret= PostData(objstr);
				String response= CopeResponse(ret, obj.getFid());
				clsToolBox.println(response);

				Handler handler= clsPublicPara.MainHandler;
				Message message=handler.obtainMessage();
				message.what= clsCmdConst.CMD_HTTP_GOODS_INFO;
				//SLOT,机器编号,价格,冈本0.02,产品图片
				if(response!=null) {
					String[] arr=response.split(",",-1);
					if(arr.length==7) {
						clsGoodsPara para= new clsGoodsPara();
						if(para!=null) {
							int i=1;
							para.setVenderid(clsToolBox.ParseInt(arr[i++]));
							para.setPrice(clsToolBox.ParseInt(arr[i++]));
							para.setGoodsName(arr[i++]);
							para.setGoodsPic(arr[i++]);
							message.arg1=1;
							message.obj=para;
							handler.sendMessage(message);
							return ;
						} else {
							message.obj="参数数据无效";
						}
					} else {
						message.obj="数组长度无效";
					}
				} else {
					message.obj="数据获取失败";
				}
				message.arg1=0;
				handler.sendMessage(message);
				return ;
			}

			private void GenerateHeartRequest(clsHttpFrame obj) {
				String objstr = obj.ToBase64String();
				clsToolBox.println(objstr);
				String ret= PostData(objstr);
				String response= CopeResponse(ret, obj.getFid());
				clsToolBox.println(response);

				Handler handler= clsPublicPara.MainHandler;
				Message message=handler.obtainMessage();
				message.what=clsCmdConst.CMD_HTTP_HEART_DATA_PARSE;
				message.arg1=0;
				if(response!=null) {
					if(response.startsWith("HEART")) {
						message.obj=response;
						message.arg1 = 1;
					}

					LocalTradeUtils.ReadySendFileHttpTrade();
				}
				message.sendToTarget();
				return ;
			}

			private void GenerateSwipeTradeRequest(clsHttpFrame obj) {
				String objstr = obj.ToBase64String();
				clsToolBox.println(objstr);
				String ret= PostData(objstr);
				String response= CopeResponse(ret, obj.getFid());
				clsToolBox.println(response);

				Handler handler= clsPublicPara.MainHandler;
				Message message=handler.obtainMessage();
				message.what=clsCmdConst.CMD_HTTP_SWIPE_DATA_PARSE;
				message.arg1=0;
				if(response!=null) {
					if(response.startsWith("SWIPE")) {
						message.obj=response;
						message.arg1 = 1;
					}
				}
				message.sendToTarget();
				return ;
			}
		});
		//启动子线程消息循环队列
		Looper.loop();
	}

	private String PostData(String obj)  {
		try {
			clsToolBox.println(url.toString());

			HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
			httpURLConnection.setConnectTimeout(10000);
			httpURLConnection.setReadTimeout(10000);
			httpURLConnection.setDoInput(true);
			httpURLConnection.setDoOutput(true);
			httpURLConnection.setRequestMethod("POST");

			//设置请求体的类型是文本类型
			httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
			//设置请求体的长度
			byte[] data = obj.getBytes("gbk");
			httpURLConnection.setRequestProperty("Content-Length", String.valueOf(data.length));
			//获得输出流，向服务器写入数据
			OutputStream outputStream = httpURLConnection.getOutputStream();
			outputStream.write(data);

			int response = httpURLConnection.getResponseCode();            //获得服务器的响应码
			if (response == HttpURLConnection.HTTP_OK) {
				connect=true;
				TellHttpConnectBreak();
				InputStream inptStream = httpURLConnection.getInputStream();
				return dealResponseResult(inptStream);                     //处理服务器的响应结果
			}
		}
		catch (Exception e1)
		{
			connect=false;
			TellHttpConnectBreak();
			e1.printStackTrace();
		}

		return null;
	}

	private void TellHttpConnectBreak() {
		if(clsPublicPara.MainHandler!=null) {
			clsPublicPara.MainHandler.obtainMessage(clsCmdConst.CMD_PC_TELL_NET_BREAK,connect).sendToTarget();
		}
	}

	public String getServerurl() {
		return serverurl;
	}

	public void setServerurl(String serverurl) {
		this.serverurl = serverurl;
	}

	public Handler getmChildHandler() {
		return mChildHandler;
	}

	public void setmChildHandler(Handler mChildHandler) {
		this.mChildHandler = mChildHandler;
	}
}
